﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Tools.Log;
namespace Lion.WeiXin.Controllers
{
    [PermissionFilter]
    public class CategoryController : Controller
    {
        DBContext db;

        public CategoryController()
            : this(null)
        { 
            
        }
        
        public CategoryController(DBContext mockDB)
        {
            if (mockDB == null)
            {
                db = new DBContext();
            }
            else {
                db = mockDB;
            }
        }

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string name, int currentPage, int pageSize)
        {
            //数据量少的，直接查全部数据分页展示           
            List<CategoryModel> list = db.Categorys.GetList(string.Empty);
            int totalCount = list.Count;
            //如果传入条件参数
            name = HttpUtility.UrlDecode(name);
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(n => n.Name.Contains(name)).OrderBy(n=>n.Code).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }
            else
            {
                list = list.OrderBy(n=>n.Code).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
            }

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }

        public ActionResult Show(int ID)
        {
            CategoryModel model = db.Categorys.GetModel(ID);
            InitType(model.TemplateID);
            return View(model);
        }

        public ActionResult Create(string parentCode)
        {
            CategoryModel parentModel = db.Categorys.GetModel(parentCode);
            if (string.IsNullOrEmpty(parentModel.Code))
            {
                parentModel.Code = "00";
                parentModel.Name = "顶级栏目";
            }
            //根据当前栏目，计算新栏目的code值
            CategoryModel model = new CategoryModel() { ParentCode=parentModel.Code};

            List<CategoryModel> list = db.Categorys.GetList(string.Empty);
            //当前父节点子节点
            List<CategoryModel> topDics = list.Where(n => n.ParentCode == parentModel.Code).ToList();
            //自动产生一个Key 键值
            if (parentModel.Code == "00")
            {                
                if (topDics.Count == 0)
                {
                    //数据库中无一条记录,所有子节点从10开始,方便计算
                    model.Code = "10";
                }
                else
                {
                    long maxKey = topDics.Max(n => long.Parse(n.Code));
                    model.Code = (maxKey + 1).ToString();
                }

            }
            else
            {
                //查找当前节点的所有子节点，并且
                if (topDics.Count == 0)
                {
                    //无子节点 
                    model.Code = parentCode + "01";
                }
                else
                {
                    long maxKey = topDics.Max(n => long.Parse(n.Code));
                    model.Code = (maxKey + 1).ToString();
                }
            }

            InitType(0);

            return View(model);
        }

        //栏目，查询首页模板和栏目模板，栏目一级为首页模板
        private void InitType(int selectID)
        {
            //加载产品类型
            List<TemplateModel> dic_pro_types = db.Templates.GetList("TypeCode in('105002','105001')");
            List<SelectListItem> selectTypes = new List<SelectListItem>();

            selectTypes.Add(new SelectListItem() { Value = "0", Text = "请选择" });

            foreach (TemplateModel item in dic_pro_types)
            {
                if (item.AID == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Name, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Name });
                }
            }
            ViewData["selTemplate"] = selectTypes;
        }
         [ValidateInput(false)]
        public ActionResult Save(CategoryModel model)
        {
            string action = model.Action;

            //创建栏目路径url，使用平级模式创建 
            string url = string.Empty;
            if (model.Code.Length == 2)
            {
                //默认一级是根路径
                url = @"/Default.html";
            }
            else
            {
                //所有二级或二级以下的都采用2级目录显示
                url = @"/" + model.DirName + "/Default.html";
            }
            model.Url = url;

            string result = SaveStateEnum.OK.ToString();
            try
            {
                if (action == ActionEnum.Create.ToString())
                {
                    if (!db.Categorys.Exists(model.Name))
                    {                       
                        db.Categorys.Add(model);
                    }
                    else
                    {
                        result = SaveStateEnum.NO.ToString();
                    }
                    
                }
                else if (action == ActionEnum.Update.ToString())
                {
                    db.Categorys.Update(model);
                }
                else
                {
                    result = SaveStateEnum.NO.ToString();
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "数据{0}失败", action);
                result = SaveStateEnum.NO.ToString();
            }

            return Content(result);
        }

        public ActionResult Delete(string IDs)
        {
            string result = SaveStateEnum.NO.ToString();
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    db.Categorys.DeleteList(IDs);
                    result = SaveStateEnum.OK.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
            }
            return Content(result);
        }

    }
}
